import {handleResp} from "../utils/commonfunc"
import {
    openLiveReq,
    deleteLiveReq,
    starOfflineReq,
} from "../apis/goApis"

export const star = {

    state: {
        roomname: '',
        catalog: -1,
        pushURL: '',
        cid: '',
        isShowing: false,
    },

    reducers: {
        setShowing(state, payload) {
            return {
                ...state,
                isShowing: payload,
            }
        },

        setPushUrl(state, payload) {
            return {
                ...state,
                pushUrl: payload,
            }
        },

        setSDKCid(state, payload) {
            return {
                ...state,
                cid: payload,
            }
        },

        setRoomName(state, payload) {
            return {
                ...state,
                roomname: payload,
            }
        },

        setLiveCatalog(state, payload) {
            return {
                ...state,
                catalog: payload,
            }
        },
    },

    effects: (dispatch) => ({

        async doOpenLive(payload, rootState) {
            const resp = await openLiveReq(payload)

            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    const {pushUrl, cid,} = data.ok
                    dispatch.star.setPushUrl(pushUrl)
                    dispatch.star.setSDKCid(cid)
                    dispatch.star.setShowing(true)
                }
            })
        },

        async doSaveRoomName(payload, rootState) {
            const roomname = payload
            dispatch.star.setRoomName(roomname)

        },

        async doSaveLiveCatalog(payload, rootState) {
            dispatch.star.setLiveCatalog(payload)
        },

        async doStarOffline(payload, rootState) {
            const resp = await starOfflineReq(payload)

            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    dispatch.star.setShowing(false)
                }
            })
        },

        async doDeleteLive(payload, rootState) {
            const resp = await deleteLiveReq(payload)

            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    dispatch.star.setShowing(false)
                }
            })
        },

    }),

}

